package cn.com.pc.penguin.controllers.admin;

import cn.com.pc.penguin.builder.keyword.KeywordSearchArgs;
import cn.com.pc.penguin.service.PenguinSearchResults;
import cn.com.pc.penguin.service.PenguinService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLDecoder;
import java.util.List;

@Controller
public class PenguinSearchController {

    @Autowired
    private PenguinService penguinService;

    @RequestMapping("/search")
    @ResponseBody
    public String search(@RequestParam String q, @RequestParam int offset, @RequestParam int limit) {
        JSONArray jsonArray = new JSONArray();
        try {
            String keyword = URLDecoder.decode(q, "utf-8");
            //System.out.println("-----------------------"+keyword);
            KeywordSearchArgs args = new KeywordSearchArgs();
            args.setRecommendion(keyword);
            args.setOffset(offset);
            args.setLimit(limit);
            PenguinSearchResults result = penguinService.search(args);
            List<String> results = result.getLists();
            for (String res : results) {
                JSONObject jb = new JSONObject();
                jb.put("name", res);
                jsonArray.put(jb);
            }
            // return jsonArray.toString();
            JSONObject jb1 = new JSONObject();
            jb1.put("data", jsonArray);
            jb1.put("total", result.getTotal());
            return jb1.toString();
            //return callback + "(" + jb1.toString() + ")";
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return "err";
    }
}
